package uploader

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

var BaseObjectUploaderMap = make(map[string]BaseObjectUploader)
var UploaderMap = map[string]BaseObjectUploader{
	"alioss": &AliOssUploader{},
}

type BaseObjectUploader interface {
	DoUpload(filePath []string)
}

func DoUploadBase(filePath []string, uploadMode string, settingPathPar string) {
	uploader := initUploader(uploadMode, settingPathPar)
	BaseObjectUploaderMap[uploadMode] = uploader
	uploader.DoUpload(filePath)
}

func parseJsonSetting(path string) ([]byte, error) {
	inputFile, inputError := os.Open(path)
	if inputError != nil {
		fmt.Println("打开配置文件出错，请检查")
		return nil, inputError
	}

	settingByte, _ := ioutil.ReadAll(inputFile)

	defer inputFile.Close()

	return settingByte, nil
}

func initUploader(uploadMode string, settingPathPar string) BaseObjectUploader {
	jsonSetting, err := parseJsonSetting(settingPathPar)
	if err != nil {
		fmt.Println("读取配置出现问题:", err)
		os.Exit(-1)
	}

	setting := make(map[string]interface{})
	// 把配置读到uploader
	json.Unmarshal(jsonSetting, &setting)

	b, err2 := json.Marshal(setting[uploadMode])
	if err2 != nil {
		fmt.Println("解析配置出现问题:", err)
		os.Exit(-1)
	}

	ba := UploaderMap[uploadMode]
	json.Unmarshal(b, &ba)

	return ba
}
